"""
证件照处理路由模块

该模块提供证件照处理的RESTful API接口，包括：
1. 获取可用尺寸列表
2. 处理证件照
3. 获取处理结果
4. 文件管理接口
"""

from fastapi import APIRouter, HTTPException, UploadFile, File, Form, BackgroundTasks, Header
from fastapi.responses import FileResponse
from typing import List, Optional
import os
import uuid
from pathlib import Path
import shutil

from api.id_photo_service import IDPhotoService
from config import STORAGE_CONFIG
from utils.file_manager import logger

router = APIRouter(prefix="/api/idphoto", tags=["证件照处理"])
service = IDPhotoService()


@router.get("/sizes", response_model=dict)
async def get_available_sizes():
    """
    获取可用的证件照尺寸列表

    Returns:
        {
            "sizes": [
                {
                    "name": "尺寸名称",
                    "dimensions": [宽度, 高度],
                    "description": "尺寸描述"
                }
            ]
        }
    """
    try:
        sizes = service.get_available_sizes()
        return {"sizes": sizes}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/colors", response_model=dict)
async def get_background_colors():
    """
    获取可用的背景颜色列表

    Returns:
        {
            "colors": ["蓝色", "白色", "红色", ...]
        }
    """
    try:
        colors = service.get_background_colors()
        return {"colors": colors}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/process", response_model=dict)
async def process_id_photo(
    background_tasks: BackgroundTasks,
    file: UploadFile = File(..., description="输入图片文件"),
    size_name: str = Form("一寸", description="证件照尺寸"),
    background_color: str = Form("蓝色", description="背景颜色"),
    watermark_option: str = Form("不添加", description="是否添加水印"),
    watermark_text: str = Form("", description="水印文字"),
    language: str = Form("zh", description="语言代码"),
    openid: str = Header(None, description="用户openid")
):
    """
    处理证件照

    Args:
        file: 输入图片文件（支持jpg、png格式）
        size_name: 证件照尺寸名称
        background_color: 背景颜色
        watermark_option: 是否添加水印（"不添加"或"添加"）
        watermark_text: 水印文字内容
        language: 语言代码（"zh", "en", "ko", "ja"）

    Returns:
        {
            "success": true,
            "message": "处理成功",
            "data": {
                "standard": "标准证件照路径",
                "hd": "高清证件照路径",
                "transparent_standard": "透明标准照路径",
                "transparent_hd": "透明高清照路径",
                "layout": "排版照路径",
                "social_media": [
                    {
                        "image": "社交媒体图片路径",
                        "caption": "图片描述"
                    }
                ],
                "metadata": {
                    "original_image": "原始图片路径",
                    "size": "尺寸名称",
                    "background_color": "背景颜色",
                    "watermark": false,
                    "watermark_text": "",
                    "language": "zh",
                    "processing_time_seconds": 2.5,
                    "created_at": "2024-01-01T12:00:00"
                }
            },
            "timestamp": "2024-01-01T12:00:00"
        }
    """
    try:
        # 验证文件类型
        if not file.content_type or not file.content_type.startswith('image/'):
            raise HTTPException(status_code=400, detail="请上传图片文件")

        # 根据openid创建用户临时目录
        if openid:
            temp_dir = Path("temp") / openid
            temp_dir.mkdir(parents=True, exist_ok=True)
        else:
            temp_dir = Path("temp")
            temp_dir.mkdir(exist_ok=True)
            
        temp_filename = f"{uuid.uuid4()}_{file.filename}"
        temp_path = temp_dir / temp_filename

        # 保存上传的文件
        with open(temp_path, "wb") as buffer:
            shutil.copyfileobj(file.file, buffer)

        # 处理证件照
        result = service.process_photo(
            input_image=str(temp_path),
            size_name=size_name,
            background_color=background_color,
            watermark_option=watermark_option,
            watermark_text=watermark_text,
            language=language,
            openid=openid
        )

        # 后台任务：清理临时文件
        def cleanup_temp_file():
            try:
                if temp_path.exists():
                    temp_path.unlink()
            except Exception as e:
                logger.warning(f"清理临时文件失败: {e}")

        background_tasks.add_task(cleanup_temp_file)

        if not result["success"]:
            raise HTTPException(status_code=400, detail=result["message"])

        return result

    except HTTPException:
        raise
    except Exception as e:
        logger.error(f"处理证件照失败: {e}")
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/files", response_model=dict)
async def list_processed_files(
    file_type: Optional[str] = None,
    limit: int = 50,
    offset: int = 0,
    openid: str = Header(None, description="用户openid")
):
    """
    列出已处理的文件

    Args:
        file_type: 文件类型过滤（standard, hd, transparent, layout, social_media）
        limit: 返回文件数量限制
        offset: 偏移量
        openid: 用户openid

    Returns:
        {
            "files": [
                {
                    "path": "文件路径",
                    "filename": "文件名",
                    "size": 1024,
                    "created_at": "2024-01-01T12:00:00",
                    "file_type": ".png",
                    "openid": "用户openid"
                }
            ],
            "total": 100,
            "offset": 0,
            "limit": 50
        }
    """
    try:
        files = service.list_processed_files(file_type, openid)
        total = len(files)
        paginated_files = files[offset:offset + limit]

        return {
            "files": paginated_files,
            "total": total,
            "offset": offset,
            "limit": limit
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/stats", response_model=dict)
async def get_storage_stats():
    """
    获取存储统计信息

    Returns:
        {
            "base_dir": "/path/to/storage",
            "total_files": 100,
            "total_size": 10485760,
            "directories": {
                "standard": {
                    "path": "/path/to/standard",
                    "file_count": 25,
                    "total_size": 2621440
                }
            },
            "last_cleanup": {
                "total_files": 50,
                "deleted_files": 10,
                "freed_space": 1048576,
                "cleanup_date": "2024-01-01T12:00:00"
            }
        }
    """
    try:
        stats = service.get_storage_stats()
        return stats
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.post("/cleanup", response_model=dict)
async def cleanup_old_files(days: Optional[int] = None):
    """
    手动触发清理过期文件

    Args:
        days: 保留天数，如果为None则使用默认值（7天）

    Returns:
        {
            "total_files": 100,
            "deleted_files": 20,
            "freed_space": 2097152,
            "cleanup_date": "2024-01-01T12:00:00"
        }
    """
    try:
        result = service.cleanup_old_files(days)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.get("/download/{file_path:path}")
async def download_file(file_path: str):
    """
    下载文件

    Args:
        file_path: 相对于存储目录的文件路径

    Returns:
        文件内容
    """
    try:
        # 构建完整路径
        full_path = STORAGE_CONFIG["base_dir"] / file_path

        if not full_path.exists():
            raise HTTPException(status_code=404, detail="文件不存在")

        # 验证文件在存储目录内
        try:
            full_path.resolve().relative_to(STORAGE_CONFIG["base_dir"].resolve())
        except ValueError:
            raise HTTPException(status_code=403, detail="访问被拒绝")

        return FileResponse(
            path=str(full_path),
            filename=full_path.name,
            media_type="image/png"
        )

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))


@router.delete("/files/{file_path:path}", response_model=dict)
async def delete_file(file_path: str):
    """
    删除文件

    Args:
        file_path: 相对于存储目录的文件路径

    Returns:
        {
            "success": true,
            "message": "文件已删除"
        }
    """
    try:
        # 构建完整路径
        full_path = STORAGE_CONFIG["base_dir"] / file_path

        if not full_path.exists():
            raise HTTPException(status_code=404, detail="文件不存在")

        # 验证文件在存储目录内
        try:
            full_path.resolve().relative_to(STORAGE_CONFIG["base_dir"].resolve())
        except ValueError:
            raise HTTPException(status_code=403, detail="访问被拒绝")

        # 删除文件
        success = service.file_manager.delete_file(str(full_path))

        if success:
            return {"success": True, "message": "文件已删除"}
        else:
            raise HTTPException(status_code=500, detail="删除文件失败")

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))